package com.wenx.v3system.modular.cloud.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wenx.v3system.modular.cloud.domain.po.SysDepartmentUser;
import com.wenx.v3system.modular.cloud.mapper.SysDepartmentUserMapper;
import com.wenx.v3system.modular.cloud.service.SysDepartmentUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统部门用户服务实现类
 * 
 * @author wenx
 */
@Slf4j
@Service
public class SysDepartmentUserServiceImpl extends ServiceImpl<SysDepartmentUserMapper, SysDepartmentUser> implements SysDepartmentUserService {

    @Override
    public List<Long> getDepartmentIdsByUserId(Long userId) {
        LambdaQueryWrapper<SysDepartmentUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartmentUser::getUserId, userId);
        List<SysDepartmentUser> departmentUsers = list(wrapper);
        return departmentUsers.stream()
                .map(SysDepartmentUser::getDepartmentId)
                .collect(Collectors.toList());
    }

    @Override
    public List<Long> getUserIdsByDepartmentId(Long departmentId) {
        LambdaQueryWrapper<SysDepartmentUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartmentUser::getDepartmentId, departmentId);
        List<SysDepartmentUser> departmentUsers = list(wrapper);
        return departmentUsers.stream()
                .map(SysDepartmentUser::getUserId)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignDepartmentsToUser(Long userId, List<Long> departmentIds) {
        // 先删除用户的现有部门关联
        removeUserDepartments(userId);
        
        // 添加新的部门关联
        if (CollUtil.isNotEmpty(departmentIds)) {
            List<SysDepartmentUser> departmentUsers = departmentIds.stream()
                    .map(departmentId -> {
                        SysDepartmentUser departmentUser = new SysDepartmentUser();
                        departmentUser.setUserId(userId);
                        departmentUser.setDepartmentId(departmentId);
                        return departmentUser;
                    })
                    .collect(Collectors.toList());
            saveBatch(departmentUsers);
            log.info("用户部门分配成功: userId={}, departmentIds={}", userId, departmentIds);
        } else {
            log.info("清空用户部门关联: userId={}", userId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeUserDepartments(Long userId) {
        LambdaQueryWrapper<SysDepartmentUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartmentUser::getUserId, userId);
        // 使用物理删除避免唯一约束冲突
        int deletedCount = baseMapper.delete(wrapper);
        log.info("物理删除用户部门关联记录数: {}, 用户ID: {}", deletedCount, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeDepartmentUsers(Long departmentId) {
        LambdaQueryWrapper<SysDepartmentUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartmentUser::getDepartmentId, departmentId);
        // 使用物理删除避免唯一约束冲突
        int deletedCount = baseMapper.delete(wrapper);
        log.info("物理删除部门用户关联记录数: {}, 部门ID: {}", deletedCount, departmentId);
    }

    @Override
    public boolean isUserInDepartment(Long userId, Long departmentId) {
        LambdaQueryWrapper<SysDepartmentUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartmentUser::getUserId, userId)
                .eq(SysDepartmentUser::getDepartmentId, departmentId);
        return count(wrapper) > 0;
    }
}